#!/bin/bash

test "${ACTION}" = "add" || exit 0
echo "${DEVNAME}" | grep -E "^/dev/input/event[0-9]+$" || exit 0

PARENTHASH=$(evsieve-helper parent "${DEVNAME}" input usb)
BASEFILE="/var/run/virtual-gun4ir-devices.${PARENTHASH}"
PIDFILE="${BASEFILE}.pid"
LOCKFILE="${BASEFILE}.lock"
LOGFILE="${BASEFILE}.log"

unlockAndExit() {
    rmdir "${LOCKFILE}"
    exit "${1}"
}

checkRunningPIDAndExit1() {
    test ! -e "${PIDFILE}" && return 0
    LPID=$(cat "${PIDFILE}")
    test ! -d "/proc/${LPID}" && return 0
    unlockAndExit 1
}

trylock() {
    # lock
    N=0
    while ! mkdir "${LOCKFILE}"
    do
	sleep 1
	let N++
	test "${N}" -gt 30 && exit 1 # give up
    done
}

trylock
checkRunningPIDAndExit1

CHILDREN=$(evsieve-helper children "${PARENTHASH}" input usb)
NDEVS=$(echo "${CHILDREN}" | wc -l)

############
# Based on GunCon2 model
############
# Trigger                  : BTN_LEFT
# Offscreen, A, C          : BTN_RIGHT
# B                        : BTN_MIDDLE
# Start                    : KEY_1
# Select                   : KEY_5
# Thumb pad                : KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT

if test "${NDEVS}" = 3
then
    DEV1=$(echo "${CHILDREN}" | head -1           | cut -f 1)
    DEV2=$(echo "${CHILDREN}" | head -2 | tail -1 | cut -f 1)
    DEV3=$(echo "${CHILDREN}" | head -3 | tail -1 | cut -f 1)

    nohup evsieve                                              \
            --input "${DEV1}" "${DEV2}" "${DEV3}" persist=exit \
            --map key:1                btn:1                   \
            --map key:5                btn:2                   \
            --map key:up               btn:5                   \
            --map key:down             btn:6                   \
            --map key:left             btn:7                   \
            --map key:right            btn:8                   \
            --output name="Gun4ir" >/dev/null 2>"${LOGFILE}" &
    echo $! > "${PIDFILE}"
else
    unlockAndExit 1
fi

unlockAndExit 0
